package com.google.code.contactserv.func.execution;

import com.google.code.contactserv.func.model.ConsoleTest;
import com.google.code.contactserv.util.SystemUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/*
*       Copyright 2007 The semap project development team.
*
*       Licensed under the Apache License, Version 2.0 (the "License");
*       you may not use this file except in compliance with the License.
*       You may obtain a copy of the License at
*
*               http://www.apache.org/licenses/LICENSE-2.0
*
*       Unless required by applicable law or agreed to in writing, software
*       distributed under the License is distributed on an "AS IS" BASIS,
*       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*       See the License for the specific language governing permissions and
*       limitations under the License.
*
*       Created by ${user} at ${date} ${time}.
*
*       ${description}.
*
*       $Id$
*/
public class CommandExecutor implements Executor {
    private Process proc;
    private String command;
    private String workingFolder;

    public void setCommand(String cmd){
        command = cmd;
    }

    public void setWorkingFolder(String folder){
        workingFolder = folder;
    }

    public void execute(ConsoleTest test) throws IOException {
        proc = Runtime.getRuntime().exec(prepareCommandLine(test), null, new File(workingFolder));
//        proc = Runtime.getRuntime().exec("cmd /c test1.cmd");
    }

    public InputStream getInputStream() {
        return proc.getInputStream();
    }

    public OutputStream getOutputStream() {
        return proc.getOutputStream();
    }

    public void waitFor() throws InterruptedException {
        if(proc != null)
          proc.waitFor();
    }

    public int exitCode(){
        return proc.exitValue();
    }

    private String prepareCommandLine(ConsoleTest test){
        return new StringBuilder(SystemUtils.getOSCMD())
                .append(command)
                .append(' ')
                .append(test.getArguments()).toString();
    }
}
